//
// Created by leisurexi on 12/5/20.
// echo_mpserv.c
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define BUF_SIZE 30

void error_handling(char *message) {
    fputs(message, stderr);
    fputc('\n', stderr);
    exit(1);
}

void read_childproc(int sig) {
    pid_t pid;
    int status;
    pid = waitpid(-1, &status, WNOHANG);
    printf("removed proc id: %d \n", pid);
}

int main(int argc, char *argv[]) {
    int server_sock, client_sock;
    struct sockaddr_in server_addr, client_addr;

    pid_t pid;
    struct sigaction act;
    socklen_t client_addr_len;
    int str_len, state;
    char buf[BUF_SIZE];
    if (argc != 2) {
        printf("Usage : %s <port>\n", argv[0]);
        exit(1);
    }

    act.sa_handler = read_childproc;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;
    state = sigaction(SIGCHLD, &act, 0);
    server_sock = socket(AF_INET, SOCK_STREAM, 0);
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(atoi(argv[1]));

    int on = 1;
    setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

    if (bind(server_sock, (struct sockaddr *) &server_addr, sizeof(server_addr)) == -1)
        error_handling("bind() error");
    if (listen(server_sock, 5) == -1)
        error_handling("listen() error");

    while (1) {
        client_addr_len = sizeof(client_addr_len);
        client_sock = accept(server_sock, (struct sockaddr *) &client_addr, &client_addr_len);
        if (client_sock == -1)
            continue;
        else
            puts("new client connected...");

        pid = fork();
        if (pid == -1) {
            close(client_sock);
            continue;
        }

        if (pid == 0) {
            // child process
            close(server_sock);
            while ((str_len = read(client_sock, buf, sizeof(buf))) != 0)
                write(client_sock, buf, str_len);

            close(client_sock);
            puts("client disconnected...");
            return 0;
        } else {
            printf("child process id: %d\n", pid);
            // parent process
            close(client_sock);
        }
    }
    close(server_sock);
    return 0;
}
